<template>
	<view class="page-about" :style="{ direction: $store.state.dir }">
		<view style="margin-top: 40px" class="flex-layout-col flex-center">
			<u-upload :maxCount="1" @afterRead="afterRead">
				<avatar-image></avatar-image>
			</u-upload>
			<!-- <image src="@/static/icon.png" style="width: 80px; height: 80px" mode="aspectFit"></image> -->
		</view>
		<view class="about-list shadow">
			<uni-list :border="false">
				<uni-list-item class="about-item" :title="$t('login.username')" showArrow clickable
					:rightText="$store.state.user.name" />
				<uni-list-item class="about-item" :title="$t('login.phone')" showArrow clickable
					:rightText="$store.state.user.phone" @click="inputDialogToggle" />
				<uni-list-item class="about-item" title="Certificate Photo" showArrow clickable
					:rightText="user.certUrl?'已上传':'未上传'" @click="handleClick" />
				<uni-list-item class="about-item" :title="$t('login.email')" showArrow clickable
					:rightText="$store.state.user.email" />
				<uni-list-item class="about-item" :title="$t('login.myCode')" showArrow clickable
					:rightText="$store.state.user.inviteCode" />
				<uni-list-item class="about-item" :title="$t('login.inviteCode')" showArrow clickable
					:rightText="invite_code" @click="onInviteOpen" />
			</uni-list>
		</view>
		<u-button type="error" @click="handleLogoff" text="log off" style="margin-top: 80px; width: 50%"></u-button>
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="Phone Number"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<u-popup :show="isPopup" mode="center" :round="10" @close="isPopup=false" @open="onOpen">
			<view class="popup_wrap">
				<view class="popup_title">We protect your privacy</view>
				<view @click.stop="handleSheet(1)">
					<view class="popup_photo" v-if="!idcard_01">
						<image src="/static/photo.png" mode="aspectFill"></image>
					</view>
					<view class="photo_icon" v-if="idcard_01">
						<image :src="idcard_01" mode="aspectFill"></image>
					</view>
				</view>
				<view style="margin-top: 20rpx;" @click.stop="handleSheet(2)">
					<view class="popup_photo" v-if="!idcard_02">
						<image src="/static/photo.png" mode="aspectFill"></image>
					</view>
					<view class="photo_icon" v-if="idcard_02">
						<image :src="idcard_02" mode="aspectFill"></image>
					</view>
				</view>
				<view class="popup_btn">
					<view @click.stop="isPopup=false" style="border-right: 1px solid #eeeeee;color:#FF3C15">
						cancel
						</u-upload>
					</view>
					<view @click.stop="handleConfirm" style="color: #036EFC;">confirm</view>
				</view>
			</view>
		</u-popup>
		<uni-popup ref="inviteDialog" type="dialog">
			<uni-popup-dialog mode="input" title="Invite Code" @confirm="dialogInviteConfirm"
				placeholder="Invite Code"></uni-popup-dialog>
		</uni-popup>
		<u-action-sheet :actions="sheetList" cancelText="cancel" :show="isSheet" @close="isSheet=false"
			@select="handleUpload"></u-action-sheet>
	</view>
</template>

<script>
	import {
		CurrentRole,
		APP_ROLE
	} from '../../config';
	import {
		policy,
		updateUser,
		bindInviteCode,
		getInviteCode,
		logOff
	} from '../../lib/service';
	import avatarPath from '../../static/avatar.png';
	import {
		isValidEgyptianPhoneNumber
	} from "@/utils/utils";

	export default {
		data() {
			return {
				version: '',
				isCreate: CurrentRole != APP_ROLE.Client,
				isPopup: false,
				idcard_01: "",
				idcard_02: "",
				isSheet: false,
				sheetIndex: 1,
				invite_code: "", //邀请码
				// user.certUrl
				cellGroupStyle: {
					backgroundColor: '#fff',
					marginBottom: '20px',
					borderRadius: '8px'
				},
				sheetList: [{
						name: 'Photo upload',
						type: "camera"
					},
					{
						name: 'album update',
						type: "album"
					}
				],
			};
		},

		computed: {
			user() {
				return this.$store.state.user;
			}
		},
		mounted() {
			console.log('user//////', this.user.certUrl)
			if (this.user.certUrl) {
				this.idcard_01 = this.user.certUrl.split(',')[0]
				this.idcard_02 = this.user.certUrl.split(',')[1]
			}
			this.getVersion();
			this.handleInvite()
		},
		methods: {
			handleInvite() {
				getInviteCode().then((res) => {
					this.invite_code = res.data.invite_code;
					console.log('邀请码', res)
				});
			},
			inputDialogToggle() {
				this.$refs.inputDialog.open();
			},
			onInviteOpen() {
				if (!this.invite_code) {
					this.$refs.inviteDialog.open();
				}
			},
			dialogInviteConfirm(e) {
				if (!e) return;
				bindInviteCode({
					invite_code: e
				}).then((res) => {
					if (res.statusCode == 0) {
						uni.showToast({
							title: 'Already bound',
							icon: 'none',
						})
						this.handleInvite();
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
						})
					}

				});
			},
			getVersion() {
				var systemInfo = uni.getSystemInfoSync();
				// #ifdef APP
				this.version = systemInfo.appWgtVersion;
				// #endif
				// #ifdef H5
				this.version = systemInfo.appVersion;
				// #endif
			},
			handleSheet(index) {
				this.sheetIndex = index;
				this.isSheet = true;
			},
			dialogInputConfirm(val) {
				uni.showLoading();
				var user = this.$store.state.user;
				let isPhone = isValidEgyptianPhoneNumber(val);
				if (!isPhone) {
					uni.showToast({
						title: this.$t('Please enter the correct phone number to submit'),
						icon: 'none',
					})
					return;
				}
				updateUser(user.id, {
					phone: val
				}).then((res) => {
					this.$store.dispatch('updateUser', {
						phone: val
					});
					uni.hideLoading();
					this.$refs.inputDialog.close();
				});
			},
			onOpen(e) {
				console.log('open', e);
			},
			// 新增图片
			async afterRead(event) {
				let file = event.file;
				console.log('111', file)
				uni.showLoading();
				const result = await this.uploadFilePromise(file);
				updateUser(this.$store.state.user.id, {
					avatarUrl: result
				});
				this.$store.dispatch('updateUser', {
					avatarUrl: result
				});
				uni.hideLoading();
			},
			uploadFilePromise(file) {
				let name = file.name ? file.name : file.url.split('/').pop();
				return new Promise((resolve, reject) => {
					policy('head', name).then((res) => {
						let a = uni.uploadFile({
							url: res.data.signedUrl, // 仅为示例，非真实的接口地址
							filePath: file.url,
							name: 'file',
							success: (res) => {
								try {
									var data = JSON.parse(res.data);
									resolve(data.data);
								} catch (e) {
									console.log(e);
								}
							}
						});
					});
				});
			},
			handleClick(e) {
				console.log(e)
				this.isPopup = true;
			},
			// 注销账户
			handleLogoff() {
				let _this = this;
				uni.showModal({
					title: 'unsubscribe',
					content: 'Are you sure you want to log off?',
					success: (res) => {
						if (res.confirm) {
							logOff().then((res) => {
								if (res.statusCode == 0) {
									_this.$store.dispatch('removeUser');
									uni.redirectTo({
										url: '/pages/login/login'
									})
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none',
									})
								}
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			handleUpload(item) {
				let _this = this;
				uni.chooseImage({
					count: 1, // 默认9，设置图片的选择数量
					sourceType: [item.type], // 可选择来源是相机
					success: (res) => {
						console.log(res)
						// const filePath = res.tempFilePaths[0];
						const filePath = res.tempFiles[0];
						filePath.url = res.tempFilePaths[0];
						_this.handleUploadFile(filePath);
					},
					fail: (err) => {
						this.$emit("fail", err);
						// 选择失败的回调
						console.log("选择图片失败：", err);
					},
				});
			},
			async handleUploadFile(filePath) {
				uni.showLoading();
				const result = await this.uploadFilePromise(filePath);
				if (this.sheetIndex == 1) {
					this.idcard_01 = result;
				} else {
					this.idcard_02 = result;
				}
				// updateUser(this.$store.state.user.id, {
				// 	certUrl: result
				// });

				// this.$store.dispatch('updateUser', {
				// 	certUrl: result
				// });
				uni.hideLoading();
			},
			handleConfirm() {
				if (!this.idcard_01 || !this.idcard_02) {
					uni.showToast({
						title: this.$t('Please upload the ID card'),
						icon: 'none',
					})
					return;
				}
				updateUser(this.$store.state.user.id, {
					certUrl: this.idcard_01 + ',' + this.idcard_02
				});
				this.isPopup = false;
				this.$store.dispatch('updateUser', {
					certUrl: this.idcard_01 + ',' + this.idcard_02
				});

			}
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #f9fbff;
	}

	.popup_wrap {
		width: 600rpx;
		background: #FFFFFF;
		border-radius: 20rpx;

		.popup_title {
			text-align: center;
			padding: 26rpx 0;
			font-weight: 400;
			font-size: 32rpx;
			color: #999999;
		}

		.popup_photo {
			width: 474rpx;
			height: 300rpx;
			background: #CDCDCD;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0 auto;

			image {
				width: 108rpx;
				height: 95rpx;
			}
		}

		.photo_icon {
			width: 474rpx;
			height: 300rpx;
			margin: 0 auto;

			image {
				width: 474rpx;
				height: 300rpx;
				display: block;
			}
		}

		.popup_btn {
			display: flex;
			align-items: center;
			margin-top: 30rpx;
			border-top: 1px solid #eeeeee;

			view {
				width: 50%;
				height: 98rpx;
				line-height: 98rpx;
				text-align: center;
				font-size: 28rpx;
			}
		}
	}

	.page-about {
		padding: 10px;

		.about-list {
			margin-top: 60px;
			border-radius: 16px;
			overflow: hidden;
		}

		.about-item {
			height: 52px;
		}
	}
</style>